package priv.jesse.mall.web.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import priv.jesse.mall.entity.FileEntity;
import priv.jesse.mall.entity.Product;
import priv.jesse.mall.entity.pojo.ResultBean;
import priv.jesse.mall.service.ProductService;
import priv.jesse.mall.utils.FileUploadTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/video")
public class AdminVideoController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/toList.html")
    public String toList() {
        return "admin/video/videolist";
    }

    @RequestMapping("/toAdd.html")
    public String toAdd() {
        return "admin/video/add";
    }

    @RequestMapping("/toEdit.html")
    public String toEdit(int id, Map<String, Object> map,HttpServletRequest request) {
        Product product = productService.findById(id);
        String[] list=product.getImage().split("&");
        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        for(int i=0;i<list.length;i++){
            list[i]=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ list[i].replace("/","%2F").replace("\\","%2F");
        }
        product.setImagelist(list);
        map.put("product", product);
        return "admin/product/edit";
    }


    @ResponseBody
    @RequestMapping("/list.do")
    public ResultBean<List<FileEntity>> listProduct(int pageindex,@RequestParam(value = "pageSize", defaultValue = "15") int pageSize,HttpServletRequest request) {
        Pageable pageable = new PageRequest(pageindex, pageSize, null);
        List<FileEntity> list = productService.findfileAll(pageable).getContent();
        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        for(int i=0;i<list.size();i++){
            String ss=list.get(i).getPath();
            String image=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ ss.replace("/","%2F").replace("\\","%2F");
            list.get(i).setPath(image);
        }
        return new ResultBean<>(list);
    }

    @ResponseBody
    @RequestMapping("/getTotal")
    public ResultBean<Integer> getTotal() {
        Pageable pageable = new PageRequest(1, 15, null);
        int total = (int) productService.findAll(pageable).getTotalElements();
        return new ResultBean<>(total);
    }

    @RequestMapping("/del.do")
    @ResponseBody
    public ResultBean<Boolean> del(int id) {
        FileEntity fileEntity = productService.findfileById(id);
        if(fileEntity==null){
            return new ResultBean<>(true);
        }
        productService.delfileById(id);
        File file=new File(fileEntity.getPath());

       if(file.exists() && file.isFile()){
            if(file.delete()){
                return new ResultBean<>(true);
            } else {
                return new ResultBean<>(false);
            }
         } else {
          file.delete();
         return new ResultBean<>(true);
         }


    }


    @RequestMapping(method = RequestMethod.POST, value = "/addvideo.do")
    public String addvideo(HttpServletRequest request,MultipartFile file) throws Exception {
       String name= request.getParameter("title").toString();
        FileEntity entity = new FileEntity();
        FileUploadTool fileUploadTool = new FileUploadTool();
        try {
            entity = fileUploadTool.createFile(file, request);
            if (entity != null) {
                entity.setName(name);
                int i=productService.saveFile(entity);
            }
            return "admin/video/videolist";
        } catch (Exception e) {
            e.printStackTrace();
            return "admin/video/videolist";
        }

    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/update.do")
    public ResultBean<String> update(int id,
                       String title,
                       String image,
                       Double marketPrice,
                       Double shopPrice,
                       String desc,
                       int csid,
                       int csid1,
                       int isHot,
                       int salesCount,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        Product product = productService.findById(id);
        product.setTitle(title);
        product.setMarketPrice(marketPrice);
        product.setShopPrice(shopPrice);
        product.setDesc(desc);
        product.setSalesCount(salesCount);
        product.setIsHot(isHot);
        product.setCsid1(csid1);
        product.setCsid(csid);
        product.setPdate(new Date());
        product.setImage(image);
        boolean flag = false;
        try {
            productService.update(product);
            flag = true;
        } catch (Exception e) {
            throw new Exception(e);
        }
        if (!flag) {
            ResultBean<String> r = new ResultBean("更新失败");
            return r;
        }
        ResultBean<String> r = new ResultBean("更新成功");
        return r;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/img/{filename:.+}")
    public void getImage(@PathVariable(name = "filename", required = true) String filename,
                         HttpServletResponse res) throws IOException {
        File file = new File("file/" + filename);
        if (file != null && file.exists()) {
            res.setHeader("content-type", "application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            res.setContentLengthLong(file.length());
            Files.copy(Paths.get(file.toURI()), res.getOutputStream());
        }
    }


    @RequestMapping("/getImg.do")
    public String getimg(String url,HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        FileInputStream fis = new FileInputStream(url);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
        return null;
    }















}
